import React, {Component} from 'react'
import {createStore, applyMiddleware} from './redux/index'

// function createStore (reducer) {
//   let state = null
//   const listeners = []
//   const subscribe = (listener) => listeners.push(listener)
//   const getState = () => state
//   const dispatch = (action) => {
//     state = reducer(state, action)
//     listeners.forEach((listener) => listener())
//   }
//   dispatch({}) // 初始化 state
//   return { getState, dispatch, subscribe }
// }

const middleware = applyMiddleware(logger, thunkMiddleware);
const initState = {};

const themeReducer = (state, action) => {
    if (!state) return {
        themeColor: 'red'
    }
    switch (action.type) {
        case 'CHANGE_COLOR':
            return {...state, themeColor: action.themeColor}
        default:
            return state
    }
}

/**
 * redux日志记录
 * @param getState 获取当前state
 * @returns {function(*): function(*=)}
 */
function logger({getState}) {
    return next => action => {
        console.log('=======redux-log-start========')
        console.log('will dispatch', action)

        // 调用 middleware 链中下一个 middleware 的 dispatch。
        const returnValue = next(action)

        console.log('state after dispatch', getState())
        console.log('=======redux-log-end========')

        return returnValue
    }
}


//thunk实现
function thunkMiddleware({dispatch, getState}) {
    return next => action => {
        console.log('action::', action)
        return typeof action === 'function' ?
            action(dispatch, getState) :
            next(action);
    }
}



const store = createStore(themeReducer, initState, middleware)

export default store